package com.babyqiao.wallpaper.portal.component;


import com.alibaba.fastjson.JSONObject;
import com.babyqiao.wallpaper.portal.entity.WallpaperAlbum;
import com.babyqiao.wallpaper.portal.entity.WallpaperAlbumPic;
import com.babyqiao.wallpaper.portal.entity.vo.AlbumPicStatisVO;
import com.babyqiao.wallpaper.portal.entity.vo.AlbumStatisVO;
import com.babyqiao.wallpaper.portal.service.IWallpaperAlbumPicService;
import com.babyqiao.wallpaper.portal.service.IWallpaperAlbumService;
import com.babyqiao.wallpaper.portal.utils.common.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 定时任务处理类
 * @author QLZ
 * @date 2021/2/26
 */
@Component
public class Schedule {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    IWallpaperAlbumService albumService;
    @Autowired
    IWallpaperAlbumPicService albumPicService;

    /**
     *每日凌晨一点，将专辑活跃数据将进行落地，并清除缓存
     * @Author QLZ
     * @Date 2021/2/26
     *
     *  @return: void
     */

    @Scheduled(cron = "0 0 1 * * ?")
    public void ablumStatisTask() {
        // *号 必须要加，否则无法模糊查询
        String prefix = RedisKeys.ALBUM_STATIS.getKey() + "*";
        // 获取所有的key
        Set<String> keys = redisTemplate.keys(prefix);
        // 批量获取数据
        List<String> strings = redisTemplate.opsForValue().multiGet(keys);
        List<AlbumStatisVO> collect = strings.stream().map(s -> JSONObject.parseObject(s, AlbumStatisVO.class)).collect(Collectors.toList());
        List<WallpaperAlbum> albums = collect.stream().map(s -> {
            WallpaperAlbum wallpaperAlbum = new WallpaperAlbum();
            wallpaperAlbum.setId(s.getAlbumId());
            wallpaperAlbum.setHot(s.getHot().toString());
            return wallpaperAlbum;
        }).collect(Collectors.toList());
        System.out.println(collect);
        boolean b = albumService.updateBatchById(albums);
        redisTemplate.delete(keys);

    }

    /**
     *每日凌晨一点，将图片活跃数据将进行落地，并清除缓存
     * @Author QLZ
     * @Date 2021/2/26
     *
     *  @return: void
     */

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void albumPicStatisTask(){
        System.out.println("执行了定时任务");
        // *号 必须要加，否则无法模糊查询
        String prefix = RedisKeys.ALBUM_PIC_STATIS.getKey() + "*";
        // 获取所有的key
        Set<String> keys = redisTemplate.keys(prefix);
        // 批量获取数据
        List<String> strings = redisTemplate.opsForValue().multiGet(keys);
        List<AlbumPicStatisVO> collect = strings.stream().map(s -> JSONObject.parseObject(s, AlbumPicStatisVO.class)).collect(Collectors.toList());
        List<WallpaperAlbumPic> albums = collect.stream().map(s -> {
            WallpaperAlbumPic wallpaperAlbumPic = new WallpaperAlbumPic();
            wallpaperAlbumPic.setId(s.getId());
            wallpaperAlbumPic.setHot(s.getHot().toString());
            wallpaperAlbumPic.setShare(s.getShare().toString());
            return wallpaperAlbumPic;
        }).collect(Collectors.toList());
        boolean b = albumPicService.updateBatchById(albums);
        redisTemplate.delete(keys);
    }
    /**
     * 每日凌晨一点，将图片点赞数据落地。
     *
     * */

    @Scheduled(cron = "0 0 1 * * ?")
    public void albumPicLikeTask(){
        // *号 必须要加，否则无法模糊查询
        String prefix = RedisKeys.ALBUM_PIC_LIKE.getKey()+"*";
        /**
         *1.先进行模糊查找，找到所有的点赞的key
         * 2.再bitcount汇总出每个图片点赞的总数
         * 3.创建WallpaperAlbumPic实例将点赞总数，和文章id放进去，返回WallpaperAlbumPic组成的List
         * 4.批量更新WallpaperAlbumPic
         * */
        Set<WallpaperAlbumPic> execute = redisTemplate.execute((RedisCallback<Set<WallpaperAlbumPic>>) con -> {
            Set<WallpaperAlbumPic> albumPics=new HashSet<>();
            Cursor<byte[]> cursor = con.scan(new ScanOptions.ScanOptionsBuilder().match(prefix).build());

            while(cursor.hasNext()) {
                WallpaperAlbumPic albumPic=new WallpaperAlbumPic();
                byte[] next = cursor.next();
                //设置文章id
                albumPic.setId(new String(next).split(":")[1]);
                //设置点赞总数
                albumPic.setLikeIt(con.bitCount(next).toString());
                albumPics.add(albumPic);
            }
            return albumPics;

        });
        albumPicService.updateBatchById(execute);

    }


    /**
     * 每日凌晨一点，将专辑点赞数据落地。
     *
     * */

    @Scheduled(cron = "0 0 1 * * ?")
    public void albumLikeTask(){
        // *号 必须要加，否则无法模糊查询
        String prefix = RedisKeys.ALBUM_LIKE.getKey()+"*";
        /**
         *1.先进行模糊查找，找到所有的点赞的key
         * 2.再bitcount汇总出每个图片点赞的总数
         * 3.创建WallpaperAlbum实例将点赞总数，和文章id放进去，返回WallpaperAlbumPic组成的List
         * 4.批量更新WallpaperAlbum
         * */
        Set<WallpaperAlbum> execute = redisTemplate.execute((RedisCallback<Set<WallpaperAlbum>>) con -> {
            Set<WallpaperAlbum> albums=new HashSet<>();
            Cursor<byte[]> cursor = con.scan(new ScanOptions.ScanOptionsBuilder().match(prefix).build());

            while(cursor.hasNext()) {
                WallpaperAlbum album=new WallpaperAlbum();
                byte[] next = cursor.next();
                //设置文章id
                album.setId(new String(next).split(":")[1]);
                //设置点赞总数
                album.setLikeIt(con.bitCount(next).toString());
                albums.add(album);
            }
            return albums;

        });
        albumService.updateBatchById(execute);

    }

}
